<template>
  <!-- pages/user_address/user_address.wxml -->
  <view class="user-address">
    <!-- #ifndef  H5 -->
    <u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent">
      <u-navbar
          :is-back="true"
          :title-bold="true"
          :is-fixed="false"
          title="地址管理"
          title-color="#000000"
          :border-bottom="false"
          back-icon-name="arrow-leftward"
          back-icon-color="#000000"
          :background="{ background: 'rgba(256,256, 256,0)' }"
      ></u-navbar>
    </u-sticky>
    <!-- #endif -->
    <view class="no-address column-center" v-if="!hasAddress">
      <image class="img-null mt20" src="/static/images/address_null.png"></image>
      <view class="sm muted">暂无添加地址，请添加~</view>
    </view>
    <view class="address-list" v-else>

      <u-radio-group class="radio-group" @change="radioChange" v-model="defaultAddressId">
        <view
            v-for="(item, index) in addressList"
            :key="index"
            class="item  mb20"
            :data-id="item.id"
            @tap="onSelect"
        >
          <view class="address">
            <view class="consignee nr bold">
              {{ item.contact }}
              <text class="phone ml10">{{ item.telephone }}</text>
            </view>
            <view class="lighter sm mt10">
              {{ item.province }} {{ item.city }} {{ item.district }}
              {{ item.address }}
            </view>
          </view>
          <view class="operation row-between">
            <view>
              <u-radio
                  class="radio row"
                  active-color="#2D6AF4"
                  :name="item.id"

                  @change="radioChange"
              >
                <text style="color: #666666;font-size: 24rpx">默认地址</text>
              </u-radio>
            </view>
            <view class="row-center">
              <view class="row mr20" @click.stop="editAddress(item.id)">
                <image
                    class="icon-sm mr10"
                    src="/static/images/icon_edit.png"
                ></image>
                编辑
              </view>
              <view class="row ml20" :data-id="item.id" @tap.stop="showSurePop">
                <image
                    class="icon-sm mr10"
                    src="/static/images/icon_del_1.png"
                ></image>
                删除
              </view>
            </view>
          </view>
        </view>
      </u-radio-group>
    </view>
    <u-modal
        id="delete-dialog"
        v-model="deleteSure"
        :showCancelButton="true"
        confirm-text="狠心删除"
        confirm-color="#FF2C3C"
        :show-title="false"
        @confirm="delAddressFun"
        @cancel="hidePop"
    >
      <view class="column-center tips-dialog">
        <image class="icon-lg" src="/static/images/icon_warning.png"></image>
        <view style="margin-top: 30rpx">确认删除该地址吗？</view>
      </view>
    </u-modal>
    <view class="footer  fixed bg-white">
      <view class="btn bg-primary white md row-center br60" @click="addAddress"
      >新增地址
      </view
      >
    </view>
  </view>
</template>

<script>
import {getAddressLists, delAddress, setDefaultAddress} from '@/api/user'
import wechath5 from '@/utils/wechath5'
import {isWeixinClient} from '@/utils/tools'

export default {
  data() {
    return {
      addressList: [],
      hasAddress: true,
      deleteSure: false,
      currentId: 0,
      isWeixin: true,
      defaultAddressId: null // 添加默认地址ID数据
    }
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.type = options.type
    //#ifdef H5
    this.isWeixin = isWeixinClient()
    //#endif
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddressListsFun()
  },

  methods: {
    onSelect(e) {
      if (this.type) {
        let {id} = e.currentTarget.dataset
        uni.$emit('selectaddress', {
          id
        })
        uni.navigateBack()
      }
    },

    addAddress() {
      uni.navigateTo({
        url: '/pages/address_edit/address_edit'
      })
    },

    editAddress(id) {
      uni.navigateTo({
        url: `/pages/address_edit/address_edit?id=${id}`
      })
    },

    getAddressListsFun() {
      getAddressLists().then((res) => {
        if (res.code == 1) {
          if (res.data.length) {
            this.addressList = res.data
            this.hasAddress = true
            // 设置默认地址ID
            const defaultAddress = res.data.find(item => item.is_default === 1)
            console.log('默认地址ID:', defaultAddress)
            if (defaultAddress) {
              this.defaultAddressId = defaultAddress.id
            }
          } else {
            this.hasAddress = false
          }
        } else {
          this.hasAddress = false
        }
      })
    },
    radioChange(e) {
      // e 为选中的 u-radio 的 name 值
      let id = e
      console.log('选中的地址ID:', id)
      setDefaultAddress(id).then((res) => {
        if (res.code == 1) {
          this.defaultAddressId = id // 更新默认地址ID
          this.getAddressListsFun()
        }
      })
    },

    onLoadFun() {
      this.getAddressListsFun()
    },

    delAddressFun(e) {
      let id = this.currentId
      delAddress(id).then((res) => {
        if (res.code == 1) {
          this.$toast({
            title: res.msg
          })
          this.deleteSure = false
          this.getAddressListsFun()
        }
      })
    },

    getWxAddressFun() {
      // #ifdef H5
      wechath5.getWxAddress().then((res) => {
        uni.setStorageSync('wxAddress', JSON.stringify(res))
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/address_edit/address_edit`
          })
        }, 200)
      })
      // #endif
      // #ifdef MP-WEIXIN
      uni.authorize({
        scope: 'scope.address',
        success: function (res) {
          uni.chooseAddress({
            success: function (res) {
              uni.setStorageSync('wxAddress', JSON.stringify(res))
              setTimeout(() => {
                uni.navigateTo({
                  url: `/pages/address_edit/address_edit`
                })
              }, 200)
            },
            fail: function (res) {
              if (res.errMsg == 'chooseAddress:cancel')
                return this.$toast({
                  title: '取消选择'
                })
            }
          })
        },
        fail: function (res) {
          uni.showModal({
            title: '您已拒绝导入微信地址权限',
            content: '是否进入权限管理，调整授权？',

            success(res) {
              if (res.confirm) {
                uni.openSetting({
                  success: function (res) {
                  }
                })
              } else if (res.cancel) {
                return this.$toast({
                  title: '已取消！'
                })
              }
            }
          })
        }
      })
      // #endif
    },

    showSurePop: function (e) {
      this.deleteSure = true
      this.currentId = e.currentTarget.dataset.id
    },
    hidePop: function (e) {
      this.deleteSure = false
    }
  }
}
</script>
<style lang="scss">
page {
  background-image: url("../../static/images/my_bg.jpg");
  background-size: 100%;
  background-repeat: no-repeat;

  /* pages/user_address/user_address.wxss */
  .user-address {
    padding-bottom: calc(140rpx + env(safe-area-inset-bottom));

    .no-address {
      padding-top: 300rpx;
      text-align: center;
    }

    .address-list {
      margin: 10rpx 30rpx;


      .item {
        padding: 0 30rpx;
        border-radius: 16rpx;
        background-color: #ffffff;

        .address {
          padding: 20rpx 0;
          border-bottom: $-solid-border;
        }

        .operation {
          height: 80rpx;
        }
      }
    }

    .footer {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 118rpx;
      padding: 0 30rpx;
      box-sizing: content-box;
      padding-bottom: env(safe-area-inset-bottom);

      .btn {
        width: 50%;
        margin: 20rpx auto;
        //flex: 1;
        height: 80rpx;
        background-image: linear-gradient(to bottom, #6aa0ff, #2d6af4);
      }
    }
  }

  .tips-dialog {
    height: 230rpx;
    width: 100%;
  }
}

.radio-group {
  font-size: 24rpx;
  color: #666666;
}

.consignee {
  color: #030303;

}

.lighter {
  color: #656565
}

</style>
